<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/5/8
 * Time: 上午9:41
 */

namespace App\Busi\Modules\Resource;


use App\Busi\Modules\BaseBusi;
use App\Busi\Traits\CompanyStaffTrait;
use App\Busi\Traits\CompanyTrait;
use App\Busi\Traits\UserTrait;
use App\Exceptions\ErrorCode\UserError;
use App\Exceptions\UserException;
use App\Http\Requests\StaffAddRo;
use App\Models\CompanyStaff;

class CompanyStaffAddBusi extends BaseBusi
{
    use UserTrait,CompanyTrait,CompanyStaffTrait;
    public function handle(StaffAddRo $ro){

        $id = $ro->id;
        $uid = $ro->uid;
        $phone = $ro->phone;
        $name = $ro->name;
        $avatar = $ro->avatar;
        $img_host = config("admin.upload.host");
        $host_count = strlen($img_host);
        $avatar = substr($avatar,$host_count,strlen($avatar)-$host_count);
        $experience = $ro->experience;
        $is_hidden = $ro->is_hidden;
        $user = $this->getUserByUid($uid);
        if(!$user){
            throw new UserException(UserError::USER_NOT_EXIST);
        }
        $raw_company = $this->getCompanyByUid($uid);
        if(!$raw_company){
            throw new UserException(UserError::USER_NOT_AUTH);
        }
        $company_id = $raw_company['id'];
        //如果存在id,则是编辑员工信息
        if($id){
            $raw_company_staff = $this->getStaffByIdAndCompanyId($id,$company_id);
            if($raw_company_staff){
                $update = [
                    "phone"=>$phone,
                    "name"=>$name,
                    "avatar"=>$avatar,
                    "experience"=>$experience,
                    "is_hidden"=>$is_hidden,
                ];
                CompanyStaff::where("id",$id)->update($update);
                $data = [
                    "msg" =>"更新成功"
                ];
                return $data;
            }
            else{
                //如果没找到 就更新失败
                throw new UserException(UserError::USERID_NOT_EXSIT_OR_NOT_AUTH);
            }
        }
        //如果不存在用户id 则表示是新增
        else{
            $companyStaff = new CompanyStaff();
            $companyStaff->company_id = $company_id;
            $companyStaff->phone = $phone;
            $companyStaff->name = $name;
            $companyStaff->avatar = $avatar;
            $companyStaff->experience = $experience;
            $companyStaff->is_hidden = $is_hidden;
            $companyStaff->save();
            $data = [
                "msg" =>"上传成功"
            ];
            return $data;
        }

    }
}